package com.ruoci.redis.requestlimit.guava;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import com.ruoci.redis.requestlimit.redis.RequestLimit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @Author yang
 **/
@Slf4j
@Aspect
@Component
public class GuavaLimitAspect {
    /**
     *  不同的接口，不同的流量控制
     *  map的key为Limiter.key
     */
    private  final Map<String, RateLimiter> limitMap= Maps.newConcurrentMap();

    /**
     *  切点
     * @param guavaLimitAspect
     */
    @Pointcut("@annotation(guavaLimitAspect)")
    public void guavaLimitAspect(GuavaLimit guavaLimitAspect) {}

    @Around("guavaLimitAspect(guavaLimit)")
    public Object around(ProceedingJoinPoint point, GuavaLimit guavaLimit) throws Throwable{
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        GuavaLimit limit = method.getAnnotation(GuavaLimit.class);
        //key作为键放入本地缓存
        String key=limit.key();
        RateLimiter rateLimiter;
        if (!limitMap.containsKey(key)){
            // 创建令牌桶
            rateLimiter = RateLimiter.create(limit.permitsPerSecond());
            limitMap.put(key, rateLimiter);
            log.info("新建了令牌桶={}，容量={}",key,limit.permitsPerSecond());
        }
        rateLimiter = limitMap.get(key);
        // 拿令牌
        boolean acquire = rateLimiter.tryAcquire(limit.timeout(), limit.timeunit());
        // 拿不到命令，直接返回异常提示
        if (!acquire) {
            log.debug("令牌桶={}，获取令牌失败",key);
            new RuntimeException("令牌桶={}，获取令牌失败");
            return null;
        }
        return point.proceed();
    }

}
